
var CurrentUser;    //Global variable

function getName() {
    var user = JSON.parse(localStorage.getItem("loggedinUser"));
    CurrentUser = user;   //global variable
    if (user) {
        console.log("Currently logged in:  " + user["name"]);
        document.getElementById("name-goes-here").innerText = user["name"];
    } else {
        console.log("No one is logged in");
    }
}
getName(); //run the function

function populateHistory() {

    // find out who is logged in 
    var who = JSON.parse(localStorage.getItem("loggedinUser"));  //person who is logged in
    var users = JSON.parse(localStorage.getItem("users"));   //the whole users database
    let email = who["email"];                                //the person who is logged in, email
    console.log(email);
    const user = users.find(u => u.email === email);         //find the person with that email
    console.log(user);

    // get information for that user who is logged in
    if (user) {
        console.log("Currently logged in:  " + user["name"]);
        console.log("Currently count is:  " + user["count"]);
        console.log("Current history is " + user["history"][0].date);

        // get the history array
        historyArray = user["history"];

        // Sort history by date, descending order (most recent one first)
        console.log(historyArray);

        // a and b represent two elements in the array that we are sorting
        historyArray.sort((a, b) => {
            // Assuming date is in format YYYY-MM-DD, if not convert it into Date object
            return b.calories - a.calories;    //most recent one first
        });
        console.log(historyArray)

        // Loop through all sorted history to display
        historyArray.forEach((hist) => {
            // Get references to the HTML card and div to hold the history
            let historyCardTemplate = document.getElementById("postCardTemplate");
            let historyCardGroup = document.getElementById("history-goes-here");
            let onecard = historyCardTemplate.content.cloneNode(true);

            date = hist.date;
            details = hist.details;
            imageName = hist.imageName;
            count = hist.calories;

            console.log(date);
            console.log(details);
            console.log(imageName);
            console.log(count);

            onecard.querySelector(".date").innerHTML = date;
            onecard.querySelector(".count").innerHTML = count;
            onecard.querySelector(".card-description").innerHTML = details;
            onecard.querySelector('.card-image').src = " ./images/" + imageName;

            historyCardGroup.appendChild(onecard);
        })

    } else {
        console.log("No one is logged in");
    }
}
populateHistory();
